package com.rzico.sbl.ui.report.depot

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.widget.NestedScrollView
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.rzico.sbl.R
import com.rzico.sbl.databinding.FragmentReportDepotBinding
import com.rzico.sbl.model.DepotBarrelDate
import com.rzico.sbl.model.ManagerContent
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.invite.ReportInviteActivity
import com.rzico.sbl.viewmodel.ReportDepotViewModel
import com.xinnuo.common.decoration.GridVerticalDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.view.FullyGridLayoutManager
import com.xinnuo.common_ui.base.NavigationFragment
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.common_ui.view.BadgeTextView
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class ReportDepotFragment : NavigationFragment() {

    private var mBinding: FragmentReportDepotBinding? = null

    private val mTotalList = ArrayList<DepotBarrelDate>()
    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()

    override fun getViewModel() = get<ReportDepotViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentReportDepotBinding
        .inflate(inflater, container, false)
        .also { mBinding = it }
        .root

    override fun initTitle() {
        initLayout()
        initListener()

        when (userRole) {
            "8" -> {
                mList.addItems(getViewModel().chiefIcons())
                mAdapter.setDataList(mList)
            }
            "9" -> {
                mList.addItems(getViewModel().deputyIcons())
                mAdapter.setDataList(mList)
            }
        }
    }

    override fun onResume() {
        super.onResume()

        getData()

        getViewModel()
            .depotCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mList.firstOrNull {
                        it as ManagerContent
                        it.title == "出库"
                    }?.let {
                        it as ManagerContent
                        it.count =  obj.optNotNull("unconfirmed").intValue
                    }

                    mList.firstOrNull {
                        it as ManagerContent
                        it.title == "入库"
                    }?.let {
                        it as ManagerContent
                        it.count =  obj.optNotNull("debit").intValue
                    }

                    mAdapter.notifyDataSetChanged()
                }
            )
    }

    private fun initLayout() {
        mBinding?.apply {
            layout
                .homeLayout
                .invisible()

            depotIcons.apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyGridLayoutManager(getIContext(), 4)

                addItemDecoration(GridVerticalDecoration(vertical = 15f))

                mAdapter = SlimAdapter.creator()
                    .register<ManagerContent>(R.layout.item_home_icon) { jector, bean, _ ->

                        // 解构声明
                        val (title, imageId, id, _, count) = bean

                        jector.apply {
                            text(R.id.item_icon_title, title)
                            image(R.id.item_icon_img, imageId)

                            with<BadgeTextView>(R.id.item_icon_num) {
                                it.setBadgeCount(count)
                            }

                            clicked {
                                when (id) {
                                    "库管" -> startActivityEx<ReportDepotListActivity>()
                                    "出库" -> startActivityEx<ReportDepotOutActivity>()
                                    "入库" -> startActivityEx<ReportDepotInActivity>()
                                    "入空桶" -> startActivityEx<ReportInviteActivity>()
                                }
                            }
                        }
                    }
                    .attachTo(this)
            }

            depotBarrel.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTotalList.indices) ""
                    else
                        mTotalList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            depotOrder.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTotalList.indices) ""
                    else
                        mTotalList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }
    }

    private fun initListener() {
        mBinding?.apply {
            depotScroll.setOnScrollChangeListener(
                NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
                    // 变化高度范围，单位像素
                    val changeHeight = dp2px(100f)

                    // 当滑动距离 <= 指定高度的时候，改变背景的透明度，达到渐变的效果
                    if (scrollY in 0..changeHeight) {
                        // 计算透明度值
                        val alpha = scrollY.toFloat() / changeHeight
                        // 改变图片背景的透明度
                        depotImg.alpha = 1f - alpha
                        // 改变标题背景的透明度
                        depotBg.alpha = alpha
                    } else {
                        // 将图片背景设置为非透明状态
                        depotImg.alpha = 0f
                        // 将标题背景设置为透明状态
                        depotBg.alpha = 1f
                    }
                }
            )

            depotAllTime.addTimeListener { start, end, _ ->
                mBeginDate = start
                mEndDate = end

                getViewModel().cancelRequest()
                getData()
            }
        }
    }

    /**
     * 设置总数据图表数据
     */
    private fun setTotalChart() {
        mBinding?.let { binding ->
            binding.depotBarrel
                .apply {
                    if (mTotalList.none { it.d_b.intValue > 0 }
                        && mTotalList.none { it.c_b.intValue > 0 }) clear()
                    else {
                        setGroupData(
                            entries = arrayListOf(
                                mTotalList.mapIndexed { index, data ->
                                    BarEntry(
                                        index.toFloat(),
                                        data.d_b.floatValue
                                    )
                                },
                                mTotalList.mapIndexed { index, data ->
                                    BarEntry(
                                        index.toFloat(),
                                        data.c_b.floatValue
                                    )
                                }
                            ),
                            colorList = getViewModel().barrelAllColor(),
                            labelList = listOf("出库", "入库"),
                            xFromValue = 0f,
                            formatter = CustomValueFormatter()
                        )
                    }

                    animateY(500)
                }

            binding.depotOrder
                .apply {
                    if (mTotalList.none { it.d_o.intValue > 0 }
                        && mTotalList.none { it.c_o.intValue > 0 }) clear()
                    else {
                        setGroupData(
                            entries = arrayListOf(
                                mTotalList.mapIndexed { index, data ->
                                    BarEntry(
                                        index.toFloat(),
                                        data.d_o.floatValue
                                    )
                                },
                                mTotalList.mapIndexed { index, data ->
                                    BarEntry(
                                        index.toFloat(),
                                        data.c_o.floatValue
                                    )
                                }
                            ),
                            colorList = getViewModel().color5(),
                            labelList = listOf("出库", "入库"),
                            xFromValue = 0f,
                            formatter = CustomValueFormatter()
                        )
                    }

                    animateY(500)
                }
        }
    }

    /**
     * 获取桶数/订单柱状图数据
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .barrelTotal(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mTotalList.clear()
                    mTotalList.addItems(it)

                    setTotalChart()
                }
            )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

}